use std::{net::TcpStream, io::Read};
use std::sync::mpsc::{self, Receiver, Sender};
use crate::{datapack, message, request, router};
pub struct Conn {
    pub rw:TcpStream,
    pub propery:String,
}

impl Conn {
    pub fn new(rw:TcpStream) -> Self {
        let r:Receiver<Vec<u8>>;
        let w:Sender<Vec<u8>>;
        (w,r) = mpsc::channel();
        Conn { 
            rw,
            propery: String::new(),
        }
    }

    pub fn send(&self, id:u32,data:Vec<u8>) {
        //封装message消息
        let msg = message::Message{id, len: data.len() as u32, data};

        //转换成二进制流
        let data = datapack::pack(msg);
    }

    pub fn start(&mut self) {
        loop {
            let mut header = [0u8;8];
            if let Err(e) = self.rw.read_exact(&mut header) {
                println!("connection error: {}", e);
                self.stop();
                return
            }

            let (id,len) = datapack::parse_header(header);

            let mut data = vec![0u8;len as usize];

            self.rw.read_exact(&mut data).unwrap();
            let msg = message::Message{id,len,data};
            
            router::handle(self, msg)
        }
    }

    fn stop(&mut self) {
        
        // 此处应该要关闭self.rw这个套接字, 但是没找到api, 就先不处理了 ^...^
        println!("stop...")
        
    }
}